<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>模版管理</title>
    <div th:replace="common/head"></div>
</head>
<body>

<!-- main content -->
<div class="container-fluid">
    <h2>模版列表</h2>
    <div class="card">
        <div id="toolbar">
            <div aria-label="Toolbar with button groups" class="btn-toolbar d-flex bd-highlight" role="toolbar">
                <div class="input-group p-2 bd-highlight">
                    <input aria-describedby="button-addon4" class="form-control" id="templateCode"
                           placeholder="模版编码" type="text">

                    <div class="input-group-append" id="button-addon4">
                        <button class="btn btn-outline-primary btn-sm" id="queryBtn">确定</button>
                        <button class="btn btn-outline-secondary btn-sm" id="resetBtn">重置</button>
                    </div>

                    <div class="input-group-append" id="button-addon3" th:if="${admin}">
                        <button class="btn btn-outline-primary btn-sm" data-target="#templateInfo" data-toggle="modal"
                                id="addTemplateBTN">添加模版
                        </button>
                    </div>
                </div>

            </div>
        </div>
        <table data-classes="table table-hover table-striped"
               data-height="629"
               data-mobile-responsive="true"
               data-page-list="[10, 25, 50]"
               data-pagination="true"
               data-query-params="queryParams"
               data-reorderable-columns="true"
               data-side-pagination="server"
               data-toggle="table"
               data-toolbar="#toolbar"
               data-toolbar-align="right"
               data-unique-id="id"
               data-url="/api/templates/page?clientId=1&version=1.0"
               id="template-list">
            <thead>
            <tr>
                <th class="text-left" data-field="id" data-visible="false"></th>
                <th class="text-left" data-field="section">学段</th>
                <th class="text-left" data-field="templateName">模版名称</th>
                <th class="text-left" data-field="templateCode">模版编码</th>
                <th class="text-left" data-field="originalFileName">模本文件名称</th>
                <th class="text-left" data-field="size" data-formatter="dataSizeFormatter">模版大小</th>
                <th class="text-center" data-events="operateEvents" data-field="operate"
                    data-formatter="operateFormatter" data-width="100">操作
                </th>
            </tr>
            </thead>
        </table>
    </div>
</div>
<!-- // END drawer-layout__content -->

<!-- drawer -->
<!--    <div th:replace="common/menu"></div>-->
<!-- // END drawer -->

<div class="modal fade" data-backdrop="static" data-keyboard="false" id="templateInfo">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">模版信息</h4>
                <button aria-hidden="true" class="close" data-dismiss="modal" type="button">&times;</button>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form">
                    <input disabled id="operation" type="hidden">
                    <input disabled id="template_id" type="hidden">
                    <div class="form-group">
                        <div class="col-sm-10">
                            <select class="form-control" id="section" required>
                                <option selected value="CZ">初中</option>
                                <option value="GZ">高中</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <input class="form-control" id="template_code" placeholder="请输入模版编码" required type="text">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <input class="form-control" id="template_name" placeholder="请输入模版名称" required type="text">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <input id="template_file" required type="file">
                            <p class="help-block">仅支持doc、docx类型的文档，文件最大1MB。</p>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal" type="button">关闭</button>
                <button class="btn btn-primary" id="submit" type="button">提交</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->

</div>

<div th:replace="common/footer"></div>

<script src="/js/extension.js"></script>
<script th:inline="javascript">
    let $table = $('#template-list');

    function dataSizeFormatter(value, row) {
        if (value > 1024) {
            return (value / 1024).toFixed(2) + 'KB';
        } else if (value > 1024 * 1024) {
            return (value / (1024 * 1024)).toFixed(2) + 'MB';
        }
        return value + "B";
    }

    function queryParams(params) {
        params.templateCode = $('#templateCode').val();
        return params
    }

    function operateFormatter(value, row, index) {
        /*<![CDATA[*/
        let isAdmin = /*[[${admin}]]*/ false;
        /*]]>*/
        let op = [];
        if (isAdmin) {
            op.push('<a class="update" href="javascript:void(0)" title="更新">更新</a>');
            op.push('  ');
        }
        op.push('<a class="download" href="javascript:void(0)" title="下载">下载</a>');
        return op.join('');
    }

    window.operateEvents = {
        'click .update': function (e, value, row, index) {
            $('#operation').val('update');
            $('#template_id').val(row.id);

            $('#section').children('option').each(function () {
                if ($(this).text() == row.section) {
                    $(this).prop('selected', true);
                }
            });

            $('#template_code').val(row.templateCode);
            $('#template_name').val(row.templateName);
            $("#section").prop("disabled", true);
            $("#template_code").prop("disabled", true);
            $("#template_name").prop("disabled", true);
            $('#templateInfo').modal('show');
        },
        'click .download': function (e, value, row, index) {
            window.location = "/api/templates/" + row.id + "?version=1.0";
        }
    };


    $(function () {
        $('#templateInfo').on('hidden.bs.modal', function () {
            $('#template_id').val("");
            $('#template_code').val("");
            $('#template_name').val("");
            $("#template_code").prop("disabled", false);
            $("#template_name").prop("disabled", false);
            $("#section").prop("disabled", false);
        });

        $("#submit").click(function () {
            let operation = $('#operation').val();
            let file = $('#template_file')[0].files[0];
            if (operation == 'update') {
                let id = $('#template_id').val();
                updateTemplate(id, file);
            } else {
                let code = $('#template_code').val();
                let name = $('#template_name').val();
                addNewTemplate(code, name, file);
            }
        });

        function addNewTemplate(code, name, file) {
            if (code == null || code == '') {
                alert("请输入模板编码");
                return;
            }
            if (name == null || name == '') {
                alert("请输入模板名称");
                return;
            }

            if (file == null || file == '') {
                alert("请选择文件");
                return;
            }

            let section = $("#section").val();
            let template = new FormData();
            template.append("section", section);
            template.append("templateName", name);
            template.append("templateCode", code);
            template.append("file", file);
            $.ajax({
                url: '/api/templates?version=1.0',
                dataType: 'json',
                type: 'POST',
                async: false,
                data: template,
                processData: false, // 使数据不做处理
                contentType: false, // 不要设置Content-Type请求头
                success: function (data) {
                    $('#templateInfo').modal('hide');
                    reload();
                },
                error: function (response) {
                    if (response.status == 200) {
                        $('#templateInfo').modal('hide');
                        reload();
                    } else {
                        alert(response.responseText);
                    }
                }
            });
        }

        function updateTemplate(id, file) {

            if (file == null || file == '') {
                alert("请选择文件");
                return;
            }

            let template = new FormData();
            template.append("file", file);
            $.ajax({
                url: '/api/templates/' + id + '?version=1.0',
                dataType: 'json',
                type: 'PUT',
                async: false,
                data: template,
                processData: false, // 使数据不做处理
                contentType: false, // 不要设置Content-Type请求头
                success: function (data) {
                    $('#templateInfo').modal('hide');
                    reload();
                },
                error: function (response) {
                    if (response.status == 200) {
                        $('#templateInfo').modal('hide');
                        reload();
                    } else {
                        alert(response.responseText);
                    }
                }
            });

        }


        <!--region 刷新操作-->
        function reload() {
            $table.bootstrapTable('refresh');
        }

        $("#queryBtn").click(function () {
            reload();
        });
        $("#templateCode").keyup(function (event) {
            if (event.keyCode == "13") {
                //回车执行查询
                reload();
            }
        });


        $("#resetBtn").click(function () {
            reset();
        });

        function reset() {
            $('#templateCode').val('');
            $table.bootstrapTable('refreshOptions', {
                sortReset: true
            });
            reload();
        }

        <!--endregion-->

    });

</script>
</body>
</html>